package com.jsj.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

import com.jsj.dao.TopFileMapper;
import com.jsj.domain.TopFile;
import com.jsj.service.ITopFileService;
import com.jsj.utils.HammingUtil;
import com.jsj.utils.WordUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


/**
 * 文件查重Service业务层处理
 *
 * @author timec
 * @date 2022-08-21
 */
@Service
public class TopFileServiceImpl implements ITopFileService
{
    @Autowired
    private TopFileMapper topFileMapper;
    @Autowired
    private ITopFileService topFileService;
    /**
     * 查询文件查重
     *
     * @param id 文件查重主键
     * @return 文件查重
     */
    @Override
    public TopFile selectTopFileById(Long id)
    {
        return topFileMapper.selectTopFileById(id);
    }
    @Override
    public List<TopFile> query(int problemId)
    {
        return topFileMapper.query(problemId);
    }
    @Override
    public List<TopFile> query1(int problemId)
    {
        return topFileMapper.query1(problemId);
    }
    @Override
    public int update(TopFile topFile)
    {
        return topFileMapper.update(topFile);
    }
    @Override
    public int updateIn(TopFile topFile)
    {
        return topFileMapper.updateIn(topFile);
    }
    @Override
    public int delete(int id)
    {
        return topFileMapper.delete(id);
    }
    @Override
    public TopFile queryById(int id)
    {
        return topFileMapper.queryById(id);
    }
    /**
     * 查询文件查重列表
     *
     * @param topFile 文件查重
     * @return 文件查重
     */
    @Override
    public List<TopFile> selectTopFileList(TopFile topFile)
    {
        return topFileMapper.selectTopFileList(topFile);
    }

    /**
     * 新增文件查重
     *
     * @param topFile 文件查重
     * @return 结果
     */
    @Override
    public int insertTopFile(TopFile topFile)
    {
        return topFileMapper.insertTopFile(topFile);
    }

    /**
     * 修改文件查重
     *
     * @param topFile 文件查重
     * @return 结果
     */
    @Override
    public int updateTopFile(TopFile topFile)
    {
        return topFileMapper.updateTopFile(topFile);
    }

    /**
     * 批量删除文件查重
     *
     * @param ids 需要删除的文件查重主键
     * @return 结果
     */
    @Override
    public int deleteTopFileByIds(Long[] ids)
    {
        return topFileMapper.deleteTopFileByIds(ids);
    }

    /**
     * 删除文件查重信息
     *
     * @param id 文件查重主键
     * @return 结果
     */
    @Override
    public int deleteTopFileById(Long id)
    {
        return topFileMapper.deleteTopFileById(id);
    }

    @Override
    public Integer checkedd(TopFile topFile)
    {
        return topFileMapper.checkedd(topFile);
    }

    @Override
    public Integer checkmyself(TopFile topFile) {
        return topFileMapper.checkmyself(topFile);
    }
    @Override
    public List<TopFile> queryByStudent(TopFile topFile)
    {
        return topFileMapper.queryByStudent(topFile);
    }

    @Override
    public AjaxResult uploadFile(MultipartFile file) {
        // TODO: 2022/8/21 前端传递用户id、测验id、题目id
        Long userid = (long) 1;
        Integer subtopid = 1;
        Integer problemid = 1;
        try {
            // 获取文件simhash值
            String msgSimHash = WordUtil.getSimHash(file);
            // 查询所属分组的所有文件SimHash值
            TopFile topFile = new TopFile();
            String checkmark = subtopid.toString() + problemid.toString();// 查重标志=测验id+题目id
            topFile.setCheckmark(checkmark);
            List<TopFile> list = topFileService.selectTopFileList(topFile);
            //最大相似度
            double similarity = 0;
            for (TopFile tF : list) {
                if (similarity < HammingUtil.getSimilarity(msgSimHash, tF.getSimhash())) {
                    similarity = HammingUtil.getSimilarity(msgSimHash, tF.getSimhash());
                }
            }
            // 相似度处理
            similarity = (double) Math.round(similarity * 10000) / 100;
            // 查重信息
            String code = "";// 20220为通过，20221为未通过。
            String msg = "";
            if (similarity > 70) {
                code = "20221";
                msg = "未通过查重，相似度为：" + similarity + "%,大于70%";
            } else {
                code = "20220";
                msg = "恭喜你，已通过查重，相似度为：" + similarity + "%,小于70%";
                // 本地保存文件
                String group = subtopid.toString() + "/" + problemid.toString();
                // 保存文件
                WordUtil.saveFile(file, group);
                // 文件信息存入数据库
                TopFile bcTopFile = new TopFile();
                bcTopFile.setUserid(userid);
                bcTopFile.setSubtopid(subtopid);
                bcTopFile.setProblemid(problemid);
                bcTopFile.setFilename(file.getOriginalFilename());
                bcTopFile.setFilepath(group);
                bcTopFile.setSimhash(msgSimHash);
                bcTopFile.setCheckmark(checkmark);
                bcTopFile.setSimilarity(similarity);
                topFileService.insertTopFile(bcTopFile);
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("code", code);
            ajax.put("msg", msg);
            System.out.println("ajax: "+ajax);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @Override
    public AjaxResult saveMultiFile(String basePath, MultipartFile[] files) {
        if (files == null || files.length == 0) {
            System.out.println("no files uploaded");
            return AjaxResult.error("no files uploaded");
        }else if (files[0].getOriginalFilename()==null || files[0].getOriginalFilename().equals("")){
            System.out.println("Empty package: no files to be uploaded");
            return AjaxResult.error("Empty package: no files to be uploaded");
        }
        if (basePath.endsWith("/")) {
            basePath = basePath.substring(0, basePath.length() - 1);
        }
        String str = null;
        for (MultipartFile file : files) {

            String relativePath = file.getOriginalFilename();
            String filePath = basePath + "/" + relativePath;
            System.out.println("uploading " + relativePath + " to " + filePath + "......");
            makeDir(filePath);
            File dest = new File(filePath);
            try {
                file.transferTo(dest);
                System.out.println("successful upload");




                topFileService.uploadFile(file);
                File file1 = new File(filePath);
                MultipartFile cMultiFile = new MockMultipartFile("file1", file1.getName(), null, new FileInputStream(file1));
//                System.out.println(cMultiFile);
//                System.out.println(topFileService.uploadFile(cMultiFile));
                str = str +" "+topFileService.uploadFile(cMultiFile);
                file1 = null;
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
        }
        return AjaxResult.success(str);
    }

    @Override
    public void makeDir(String filePath) {
        if (filePath.lastIndexOf('/') > 0) {
            String dirPath = filePath.substring(0, filePath.lastIndexOf('/'));
            File dir = new File(dirPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }
    }
}
